package com.ehome.emergency.controller.admin;

import com.ehome.emergency.common.ApiPath;
import com.ehome.emergency.common.Constant;
import com.ehome.emergency.entities.Account;
import com.ehome.emergency.enums.Status;
import com.ehome.emergency.service.IAccountService;
import com.ehome.emergency.utils.Pager;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BasicFramework
 *
 * @author: haoxiaolei
 * @date: 2016-04-01 17:18
 * @desc: 账号管理
 */
@Controller
public class AccountController extends BaseAdminController {
    private static final Logger LOG = LoggerFactory.getLogger(AccountController.class);

    @Resource
    private IAccountService accountService;

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_ENTRY)
    public String entry() {
        LOG.info("账号管理列表页面");
        return "admin/system/account_list";
    }

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_LIST, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(Pager pager, HttpServletRequest request) {
        LOG.info("账号管理列表数据");
        Map<String, Object> resultMap = new HashMap<>();
        DetachedCriteria criteria = DetachedCriteria.forClass(Account.class);
        String tenantId = request.getSession().getAttribute(Constant.TENANT_ID).toString();
        criteria.add(Restrictions.eq("tenantId", tenantId));
        try {
            List<Account> accountList = accountService.findListPager(Account.class, criteria, pager);
            if (accountList != null && accountList.size() > 0) {
                List<Map<String, Object>> dataList = new ArrayList<>();
                Map<String, Object> dataMap;
                for (Account account : accountList) {
                    dataMap = new HashMap<>();
                    dataMap.put("id", account.getId());
                    dataMap.put("accName", account.getAccName());
                    dataMap.put("nickName", account.getNickName());
                    dataMap.put("phone", account.getPhone());
                    dataMap.put("description", account.getDescription());
                    dataMap.put("status", account.getStatus());
                    dataList.add(dataMap);
                }
                resultMap.put(Constant.STATUS, Constant.SUCCESS);
                resultMap.put(Constant.ROWS, dataList);
                resultMap.put(Constant.TOTAL, pager.getTotalRecords());
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_ADD)
    public String add() {
        LOG.info("账户管理添加页面");
        return "admin/system/account_input";
    }

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_SAVE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> save(Account account, HttpServletRequest request) {
        LOG.info("账户管理保存");
        Map<String, Object> resultMap = new HashMap<>();
        String tenantId = request.getSession().getAttribute(Constant.TENANT_ID).toString();
        try {
            account.setTenantId(tenantId);
            account.setStatus(Status.AVAILABLE.name());
            accountService.save(account);
            resultMap.put(Constant.STATUS, Constant.SUCCESS);
            resultMap.put(Constant.MSG, "保存成功");
        } catch (Exception e) {
            resultMap.put(Constant.STATUS, Constant.ERROR);
            resultMap.put(Constant.MSG, "保存失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_EDIT)
    public String edit(String id, Model model, HttpServletRequest request) {
        LOG.info("账户管理编辑页面");
        String tenantId = request.getSession().getAttribute("tenantId").toString();
        DetachedCriteria criteria = DetachedCriteria.forClass(Account.class);
        criteria.add(Restrictions.eq("id", Long.valueOf(id)));
        criteria.add(Restrictions.eq("tenantId", tenantId));
        try {
            List<Account> accountList = accountService.findList(Account.class, criteria);
            model.addAttribute("account", (accountList != null && accountList.size() > 0)?accountList.get(0) : null);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        model.addAttribute("accId", id);
        return "admin/system/account_input";
    }

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_REMOVE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> remove(String ids, HttpServletRequest request) {
        LOG.info("账户管理删除");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(ids)) {
                List<Long> idList = new ArrayList<>();
                String[] idArray = ids.split(",");
                for (String mid : idArray) {
                    idList.add(Long.valueOf(mid));
                }
                String tenantId = request.getSession().getAttribute("tenantId").toString();
                DetachedCriteria criteria = DetachedCriteria.forClass(Account.class);
                criteria.add(Restrictions.in("id", idList));
                criteria.add(Restrictions.eq("tenantId", tenantId));
                List<Account> accountList = accountService.findList(Account.class, criteria);
                accountService.delete(accountList);
                resultMap.put(Constant.STATUS, Constant.SUCCESS);
                resultMap.put(Constant.MSG, "删除成功");
            }
        } catch (Exception e) {
            resultMap.put(Constant.STATUS, Constant.ERROR);
            resultMap.put(Constant.MSG, "删除失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    /**
     * 验证账户名是否已经存在了
     * @param accId   账户Id
     * @param name    账户名称
     * @return true:不存在，可用且注册；false:已存在，不可用
     */
    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_EXISTS_NAME)
    @ResponseBody
    public boolean existsName(String accId, String name, HttpServletRequest request) {
        LOG.info("验证账户名是否已经存在了");
        boolean result = true;
        String tenantId = request.getSession().getAttribute("tenantId").toString();
        DetachedCriteria criteria = DetachedCriteria.forClass(Account.class);
        criteria.add(Restrictions.eq("tenantId", tenantId));
        criteria.add(Restrictions.eq("accName", name));
        try {
            List<Account> accountList = accountService.findList(Account.class, criteria);
            if (accountList != null && accountList.size() == 1) {
                Account oldAccount = accountList.get(0);
                result = (accId).equals(oldAccount.getId().toString());
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return result;
    }

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_ENABLE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> enable(String ids, HttpServletRequest request) {
        LOG.info("账号启用");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(ids)) {
                changeStatus(ids, Status.AVAILABLE, request);
                resultMap.put(Constant.STATUS, Constant.SUCCESS);
                resultMap.put(Constant.MSG, "启用成功");
            }
        } catch (Exception e) {
            resultMap.put(Constant.STATUS, Constant.ERROR);
            resultMap.put(Constant.MSG, "启用失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @RequestMapping(value = ApiPath.ADMIN_ACCOUNT_DISABLE, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> disable(String ids, HttpServletRequest request) {
        LOG.info("账号禁用");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(ids)) {
                changeStatus(ids, Status.UNAVAILABLE, request);
                resultMap.put(Constant.STATUS, Constant.SUCCESS);
                resultMap.put(Constant.MSG, "禁用成功");
            }
        } catch (Exception e) {
            resultMap.put(Constant.STATUS, Constant.ERROR);
            resultMap.put(Constant.MSG, "禁用失败，请联系管理员！");
            LOG.error(e.getMessage(), e);
        }
        return resultMap;
    }

    /**
     * 改变状态
     * @param ids    主键ids，以逗号分隔
     * @param status 状态
     */
    private void changeStatus(String ids, Status status, HttpServletRequest request) throws Exception {
        List idList = new ArrayList<>();
        String[] midArray = ids.split(",");
        for (String mid : midArray) {
            idList.add(Long.valueOf(mid));
        }
        String tenantId = request.getSession().getAttribute(Constant.TENANT_ID).toString();
        DetachedCriteria criteria = DetachedCriteria.forClass(Account.class);
        criteria.add(Restrictions.in("id", idList));
        criteria.add(Restrictions.eq("tenantId", tenantId));
        List<Account> accountList = accountService.findList(Account.class, criteria);
        if (accountList != null && accountList.size() > 0) {
            for (Account account : accountList) {
                account.setStatus(status.name());
            }
        }
        accountService.update(accountList);
    }





}
